---
title: "Python Snippets"
date: 2017-4-23 2018-11-21 2017-09-20 2017-04-23 2017-04-23 2017-09-30 2017-04-23 2018-11-21 2017-08-10 2017-06-30 2017-04-23 2017-04-23 2017-04-23 2017-04-23
categories:
- python
tags:
---

<div id="content">
<div id="table-of-contents">
<h2>Table of Contents</h2>
<div id="text-table-of-contents">
<ul>
<li><a href="#orge719d46">爬虫</a></li>
<li><a href="#org5e4b899">Get Mac Address</a></li>
<li><a href="#orgc9ebb07">GetPID</a></li>
<li><a href="#orge6bb8f6">Base6</a></li>
<li><a href="#org1daedc5">Current Working Directory</a></li>
<li><a href="#org60aa364">Connecting Redis</a></li>
<li><a href="#org4415223">Socket Test</a></li>
<li><a href="#org54dc5f1">Exception</a></li>
<li><a href="#orgc96c976">os.walk</a></li>
<li><a href="#orgac0cb1d">MD5</a></li>
<li><a href="#orgb0eeb11">RSA</a></li>
<li><a href="#org899252b">AES</a>
<ul>
<li><a href="#orgd2dec4f">Encrypt</a></li>
<li><a href="#org9aa5518">Decrypt</a></li>
<li><a href="#org5d05284">AESCipher Class</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div class="outline-2" id="outline-container-orge719d46">
<h2 id="orge719d46">爬虫</h2>
<div class="outline-text-2" id="text-orge719d46">
<div class="org-src-container">
<pre class="src src-python"><span style="font-weight: bold; font-style: italic;">#</span><span style="font-weight: bold; font-style: italic;">! python3</span>
<span style="font-weight: bold;">import</span> http.client, re, os, urllib.parse, sys
<span style="font-weight: bold;">from</span> bs4 <span style="font-weight: bold;">import</span> BeautifulSoup

<span style="font-weight: bold;">if</span> <span style="font-weight: bold;">len</span>(sys.argv) &lt; 2:
    <span style="font-weight: bold;">print</span>(<span style="font-style: italic;">"usage python3 %s.py &lt;url&gt;"</span> % sys.argv[0])
    sys.<span style="font-weight: bold; text-decoration: underline;">exit</span>(0)

<span style="font-weight: bold;">def</span> <span style="font-weight: bold;">split_url</span>(url):
    <span style="font-weight: bold;">if</span> <span style="font-weight: bold;">not</span> url.startswith(<span style="font-style: italic;">'http://'</span>) <span style="font-weight: bold;">and</span> <span style="font-weight: bold;">not</span> url.startswith(<span style="font-style: italic;">'https://'</span>):
        <span style="font-weight: bold; font-style: italic;">url</span> = <span style="font-style: italic;">"http://%s"</span> % url
    <span style="font-weight: bold; font-style: italic;">protocol</span>, <span style="font-weight: bold; font-style: italic;">temp</span> = urllib.parse.splittype(url)
    <span style="font-weight: bold; font-style: italic;">host</span>, <span style="font-weight: bold; font-style: italic;">path</span> = urllib.parse.splithost(temp)
    <span style="font-weight: bold; font-style: italic;">port</span> = <span style="font-weight: bold; text-decoration: underline;">None</span>
    <span style="font-weight: bold;">if</span> host <span style="font-weight: bold;">is</span> <span style="font-weight: bold;">not</span> <span style="font-weight: bold; text-decoration: underline;">None</span>:
        <span style="font-weight: bold; font-style: italic;">host</span>, <span style="font-weight: bold; font-style: italic;">port</span> = urllib.parse.splitport(host)
    <span style="font-weight: bold;">if</span> port <span style="font-weight: bold;">is</span> <span style="font-weight: bold; text-decoration: underline;">None</span>:
        <span style="font-weight: bold;">if</span> protocol == <span style="font-style: italic;">"http"</span>:
            <span style="font-weight: bold; font-style: italic;">port</span> = 80
        <span style="font-weight: bold;">else</span>:
            <span style="font-weight: bold; font-style: italic;">port</span> = 443
    <span style="font-weight: bold;">if</span> path <span style="font-weight: bold;">is</span> <span style="font-weight: bold; text-decoration: underline;">None</span>:
        <span style="font-weight: bold; font-style: italic;">path</span> = <span style="font-style: italic;">"/"</span>
    <span style="font-weight: bold;">return</span> (protocol, host, port, path)

<span style="font-weight: bold; font-style: italic;">protocol</span>, <span style="font-weight: bold; font-style: italic;">HOST</span>, <span style="font-weight: bold; font-style: italic;">PORT</span>, <span style="font-weight: bold; font-style: italic;">PATH</span> = split_url(sys.argv[1])
<span style="font-weight: bold; font-style: italic;">IS_SECURED</span> = protocol == <span style="font-style: italic;">"https"</span>

<span style="font-weight: bold;">def</span> <span style="font-weight: bold;">create_url</span>(is_secured, host, port):
    <span style="font-weight: bold; font-style: italic;">prefix</span> = <span style="font-style: italic;">"http"</span>
    <span style="font-weight: bold;">if</span> is_secured:
        <span style="font-weight: bold; font-style: italic;">prefix</span> = <span style="font-style: italic;">"https"</span>
    <span style="font-weight: bold;">if</span> port <span style="font-weight: bold;">is</span> <span style="font-weight: bold; text-decoration: underline;">None</span>:
        <span style="font-weight: bold;">return</span> <span style="font-style: italic;">"%s://%s"</span> % (prefix, host)
    <span style="font-weight: bold;">else</span>:
        <span style="font-weight: bold;">return</span> <span style="font-style: italic;">"%s://%s:%d"</span> % ( prefix, host, port)

<span style="font-weight: bold;">def</span> <span style="font-weight: bold;">get_status</span>(is_secured, host, port, path):
    <span style="font-weight: bold; font-style: italic;">conn</span> = <span style="font-weight: bold; text-decoration: underline;">None</span>
    <span style="font-weight: bold;">if</span> port <span style="font-weight: bold;">is</span> <span style="font-weight: bold; text-decoration: underline;">None</span>:
        <span style="font-weight: bold; font-style: italic;">port</span> = 80
    <span style="font-weight: bold;">if</span> is_secured:
        <span style="font-weight: bold; font-style: italic;">conn</span> = http.client.HTTPSConnection(host, port)
    <span style="font-weight: bold;">else</span>:
        <span style="font-weight: bold; font-style: italic;">conn</span> = http.client.HTTPConnection(host, port)
    conn.request(<span style="font-style: italic;">"GET"</span>, path)
    <span style="font-weight: bold; font-style: italic;">resp</span> = conn.getresponse()
    <span style="font-weight: bold;">return</span> resp.status


<span style="font-weight: bold; font-style: italic;">urls</span> = [PATH]
<span style="font-weight: bold; font-style: italic;">i</span> = 0

<span style="font-weight: bold; font-style: italic;">label</span> = {
        <span style="font-style: italic;">"link"</span>: <span style="font-style: italic;">'href'</span>,
        <span style="font-style: italic;">'script'</span>: <span style="font-style: italic;">'src'</span>,
        <span style="font-style: italic;">'a'</span>: <span style="font-style: italic;">'href'</span>
        }

<span style="font-weight: bold;">while</span> i&lt;<span style="font-weight: bold;">len</span>(urls):
    <span style="font-weight: bold; font-style: italic;">url</span> = urls[i]
    <span style="font-weight: bold; font-style: italic;">i</span> = i + 1
    <span style="font-weight: bold; font-style: italic;">protocol</span>, <span style="font-weight: bold; font-style: italic;">rest</span> = urllib.parse.splittype(url)
    <span style="font-weight: bold; font-style: italic;">host</span>, <span style="font-weight: bold; font-style: italic;">path</span> = urllib.parse.splithost(rest)
    <span style="font-weight: bold;">if</span> host <span style="font-weight: bold;">is</span> <span style="font-weight: bold;">not</span> <span style="font-weight: bold; text-decoration: underline;">None</span>:
        <span style="font-weight: bold; font-style: italic;">host</span>, <span style="font-weight: bold; font-style: italic;">port</span> = urllib.parse.splitport(host)
        <span style="font-weight: bold;">if</span> host != HOST <span style="font-weight: bold;">or</span> port != PORT:
            <span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">out link</span>
            <span style="font-weight: bold; font-style: italic;">status</span> = get_status(protocol == <span style="font-style: italic;">"https"</span>, host, port, path)
            <span style="font-weight: bold;">print</span>(<span style="font-style: italic;">"%d %s"</span> % (status, url))
            <span style="font-weight: bold;">continue</span>
    <span style="font-weight: bold; font-style: italic;">conn</span> = http.client.HTTPConnection(HOST, PORT)
    conn.request(<span style="font-style: italic;">"GET"</span>, url)
    <span style="font-weight: bold; font-style: italic;">response</span> = conn.getresponse()
    <span style="font-weight: bold;">print</span>(<span style="font-style: italic;">"%d %s"</span> % (response.status, url))
    <span style="font-weight: bold;">if</span> response.status == 200:
        <span style="font-weight: bold; font-style: italic;">fname</span>, <span style="font-weight: bold; font-style: italic;">ext</span> = os.path.splitext(url)
        <span style="font-weight: bold;">if</span> ext <span style="font-weight: bold;">in</span> (<span style="font-style: italic;">'.jpg'</span>, <span style="font-style: italic;">'.png'</span>, <span style="font-style: italic;">'.gif'</span>, <span style="font-style: italic;">'.bmp'</span>, <span style="font-style: italic;">'.css'</span>, <span style="font-style: italic;">'.js'</span>):
            <span style="font-weight: bold;">pass</span>
        <span style="font-weight: bold; font-style: italic;">body</span> = response.read()
        <span style="font-weight: bold; font-style: italic;">soup</span> = BeautifulSoup(body, features=<span style="font-style: italic;">"html.parser"</span>)
        <span style="font-weight: bold;">for</span> ele, attr <span style="font-weight: bold;">in</span> label.items():
            <span style="font-weight: bold; font-style: italic;">links</span> = soup.find_all(ele)
            <span style="font-weight: bold;">for</span> ele <span style="font-weight: bold;">in</span> links:
                <span style="font-weight: bold; font-style: italic;">href</span> = ele.get(attr)
                <span style="font-weight: bold;">if</span> href <span style="font-weight: bold;">is</span> <span style="font-weight: bold; text-decoration: underline;">None</span> <span style="font-weight: bold;">or</span> href <span style="font-weight: bold;">in</span> urls:
                    <span style="font-weight: bold;">continue</span>
                <span style="font-weight: bold;">if</span> href.startswith(<span style="font-style: italic;">'../'</span>):
                    <span style="font-weight: bold;">print</span>(<span style="font-style: italic;">"relative path"</span>)
                    <span style="font-weight: bold;">if</span> <span style="font-weight: bold;">not</span> path.endswith(<span style="font-style: italic;">'/'</span>):
                        <span style="font-weight: bold; font-style: italic;">path</span> = os.path.dirname(path)
                    <span style="font-weight: bold; font-style: italic;">path</span> = os.path.join(path, ele)
                    <span style="font-weight: bold; font-style: italic;">href</span> = os.path.normpath(path)
                urls.append(href)

</pre>
</div>
</div>
</div>
<div class="outline-2" id="outline-container-org5e4b899">
<h2 id="org5e4b899">Get Mac Address</h2>
<div class="outline-text-2" id="text-org5e4b899">
<div class="org-src-container">
<pre class="src src-python"><span style="font-weight: bold;">def</span> <span style="font-weight: bold;">get_mac_addr</span>():
    <span style="font-weight: bold;">import</span> uuid
    <span style="font-weight: bold; font-style: italic;">node</span> = uuid.getnode()
    <span style="font-weight: bold; font-style: italic;">mac</span> = uuid.UUID(<span style="font-weight: bold;">int</span> = node).<span style="font-weight: bold;">hex</span>[-12:]
    <span style="font-weight: bold;">return</span> mac
</pre>
</div>
</div>
</div>
<div class="outline-2" id="outline-container-orgc9ebb07">
<h2 id="orgc9ebb07">GetPID</h2>
<div class="outline-text-2" id="text-orgc9ebb07">
<div class="org-src-container">
<pre class="src src-python"><span style="font-weight: bold;">import</span> os
<span style="font-weight: bold;">import</span> sys
<span style="font-weight: bold;">import</span> string
<span style="font-weight: bold;">import</span> psutil
<span style="font-weight: bold;">import</span> re

<span style="font-weight: bold;">def</span> <span style="font-weight: bold;">get_pid</span>(name):
        <span style="font-weight: bold; font-style: italic;">process_list</span> = psutil.get_process_list()
        <span style="font-weight: bold; font-style: italic;">regex</span> = <span style="font-style: italic;">"pid=(\d+),\sname=\'"</span> + name + <span style="font-style: italic;">"\'"</span>
        <span style="font-weight: bold;">print</span>(regex)
        <span style="font-weight: bold; font-style: italic;">ini_regex</span> = re.<span style="font-weight: bold;">compile</span>(regex)
        <span style="font-weight: bold; font-style: italic;">pid</span> = 0
        <span style="font-weight: bold;">for</span> line <span style="font-weight: bold;">in</span> process_list:
                <span style="font-weight: bold; font-style: italic;">process_info</span> = <span style="font-weight: bold;">str</span>(line)
                <span style="font-weight: bold; font-style: italic;">result</span> = ini_regex.search(process_info)
                <span style="font-weight: bold;">if</span> result != <span style="font-weight: bold; text-decoration: underline;">None</span>:
                        <span style="font-weight: bold; font-style: italic;">pid</span> = string.atoi(result.group(1))
                        <span style="font-weight: bold;">print</span>(result.group())
                        <span style="font-weight: bold;">break</span>

<span style="font-weight: bold;">def</span> <span style="font-weight: bold;">main</span>(argv):
        <span style="font-weight: bold; font-style: italic;">name</span> = argv[1]
        get_pid(name)

main(sys.argv)
</pre>
</div>
</div>
</div>
<div class="outline-2" id="outline-container-orge6bb8f6">
<h2 id="orge6bb8f6">Base6</h2>
<div class="outline-text-2" id="text-orge6bb8f6">
<div class="org-src-container">
<pre class="src src-python"><span style="font-weight: bold;">import</span> base64

<span style="font-weight: bold;">str</span> = <span style="font-style: italic;">"hello world"</span>
<span style="font-weight: bold; font-style: italic;">encode</span> = base64.b64encode(<span style="font-weight: bold;">bytes</span>(<span style="font-weight: bold;">str</span>, <span style="font-style: italic;">'utf-8'</span>));
<span style="font-weight: bold;">print</span>(encode)

<span style="font-weight: bold; font-style: italic;">decode</span> = base64.b64decode(encode)
<span style="font-weight: bold;">print</span>(decode)
</pre>
</div>
</div>
</div>
<div class="outline-2" id="outline-container-org1daedc5">
<h2 id="org1daedc5">Current Working Directory</h2>
<div class="outline-text-2" id="text-org1daedc5">
<div class="org-src-container">
<pre class="src src-python"><span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">https://stackoverflow.com/questions/2817264/how-to-get-the-parent-dir-location</span>

<span style="font-weight: bold;">import</span> sys
<span style="font-weight: bold;">import</span> os

<span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">sys.path</span>
<span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">字符串列表，指定模块的搜索路径，第0个元素是当前脚本的路径</span>
<span style="font-weight: bold;">print</span>(<span style="font-style: italic;">"sys.path[0] = "</span> + sys.path[0]) <span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">This won't work if you're running from inside an interpreter</span>
<span style="font-weight: bold;">print</span>(<span style="font-style: italic;">"parent path = "</span> + os.path.dirname(sys.path[0])) <span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">applying dirname to a directory yields the parent directory</span>


<span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">you'll get NameError: name '__file__' is not defined</span>
<span style="font-weight: bold;">print</span>(<span style="font-style: italic;">"__file__ = "</span> + __file__)
<span style="font-weight: bold; font-style: italic;">realpath</span> = os.path.realpath(__file__)
<span style="font-weight: bold;">print</span>(<span style="font-style: italic;">"os.path.realpath(__file__) == "</span> + realpath)
<span style="font-weight: bold; font-style: italic;">dn</span> = os.path.dirname(realpath)
<span style="font-weight: bold;">print</span>(<span style="font-style: italic;">"os.path.dirname(realpath) == "</span> + dn)

</pre>
</div>
</div>
</div>
<div class="outline-2" id="outline-container-org60aa364">
<h2 id="org60aa364">Connecting Redis</h2>
<div class="outline-text-2" id="text-org60aa364">
<div class="org-src-container">
<pre class="src src-python"><span style="font-weight: bold;">import</span> redis
<span style="font-weight: bold;">try</span>:
        <span style="font-weight: bold; font-style: italic;">r</span> = redis.StrictRedis(host=<span style="font-style: italic;">'127.0.0.1'</span>, port=6379)
        <span style="font-weight: bold; font-style: italic;">pingRes</span> = r.ping();
        <span style="font-weight: bold;">print</span>(pingRes);
<span style="font-weight: bold;">except</span>:
        <span style="font-weight: bold;">print</span>(<span style="font-style: italic;">'error'</span>)
</pre>
</div>
</div>
</div>
<div class="outline-2" id="outline-container-org4415223">
<h2 id="org4415223">Socket Test</h2>
<div class="outline-text-2" id="text-org4415223">
<div class="org-src-container">
<pre class="src src-python"><span style="font-weight: bold; font-style: italic;">#</span><span style="font-weight: bold; font-style: italic;">! python 3</span>
<span style="font-weight: bold;">import</span> socket

<span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">function: sendn</span>
<span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">Usage of socket.send</span>
<span style="font-weight: bold;">def</span> <span style="font-weight: bold;">send</span>(sock, data):
        <span style="font-weight: bold; font-style: italic;">p</span> = 0
        <span style="font-weight: bold; font-style: italic;">remain</span> = <span style="font-weight: bold;">len</span>(data)
        <span style="font-weight: bold;">while</span> remain:
                <span style="font-weight: bold; font-style: italic;">writen</span> = sock.send(data[p:])
                <span style="font-weight: bold;">if</span> writen &lt; 1:
                        <span style="font-weight: bold;">print</span>(<span style="font-style: italic;">'send data to server exception: write 0'</span>)
                        <span style="font-weight: bold; text-decoration: underline;">exit</span>(0)
                <span style="font-weight: bold; font-style: italic;">p</span> += writen
                <span style="font-weight: bold; font-style: italic;">remain</span> -= writen

<span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">function: recvn, will block until n size is received</span>
<span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">Show the usage of socket.recvmsg_into</span>
<span style="font-weight: bold;">def</span> <span style="font-weight: bold;">recv</span>(sock, n):
        <span style="font-weight: bold; font-style: italic;">header</span> = <span style="font-weight: bold;">bytearray</span>(n)
        <span style="font-weight: bold; font-style: italic;">remain</span> = n
        <span style="font-weight: bold;">while</span>(remain):
                (readn, ancdata, msg_flag, addr) = sock.recvmsg_into([<span style="font-weight: bold;">memoryview</span>(header)[n - remain:]])
                <span style="font-weight: bold;">if</span> readn == 0:
                        <span style="font-weight: bold;">print</span>(<span style="font-style: italic;">'server disconnected'</span>)
                        <span style="font-weight: bold; text-decoration: underline;">exit</span>(0)
                <span style="font-weight: bold; font-style: italic;">remain</span> -= readn
        <span style="font-weight: bold;">return</span> header

<span style="font-weight: bold; font-style: italic;">sock</span> = socket.socket(socket.AF_INET, socker.SOCK_STREAM) <span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">create tcp socket</span>
<span style="font-weight: bold; font-style: italic;">port</span> = 5001
<span style="font-weight: bold; font-style: italic;">host</span> = <span style="font-style: italic;">'127.0.0.1'</span>

sock.connect((host, port)) <span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">connect to remote host</span>
</pre>
</div>
</div>
</div>
<div class="outline-2" id="outline-container-org54dc5f1">
<h2 id="org54dc5f1">Exception</h2>
<div class="outline-text-2" id="text-org54dc5f1">
<div class="org-src-container">
<pre class="src src-python"><span style="font-weight: bold; font-style: italic;">i_1</span> = 1
<span style="font-weight: bold; font-style: italic;">i_2</span> = 0

<span style="font-weight: bold;">try</span>:
    i_1 / i_2
<span style="font-weight: bold;">except</span> <span style="font-weight: bold; text-decoration: underline;">Exception</span> <span style="font-weight: bold;">as</span> e:
    <span style="font-weight: bold;">print</span>(e)
<span style="font-weight: bold;">else</span>:
    <span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">if there is not exception, then execute this block</span>
    <span style="font-weight: bold;">print</span>(<span style="font-style: italic;">'code executed'</span>)

<span style="font-weight: bold;">with</span> <span style="font-weight: bold;">open</span>(<span style="font-style: italic;">'exception.py'</span>) <span style="font-weight: bold;">as</span> f:
    f.read()
    <span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">i_1 / i_2 # simulate exception</span>
<span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">if file does not exist, exception throwed, which causes application exit</span>
<span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">if file exists, i_1/i_2 throws out, and f is closed, and application exit</span>

<span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">using below to handler exception when using 'with'</span>
<span style="font-weight: bold;">try</span>:
    <span style="font-weight: bold;">with</span> <span style="font-weight: bold;">open</span>(<span style="font-style: italic;">'exception.py'</span>) <span style="font-weight: bold;">as</span> f:
        f.read()
        i_1 / i_2
<span style="font-weight: bold;">except</span> <span style="font-weight: bold; text-decoration: underline;">Exception</span> <span style="font-weight: bold;">as</span> e:
    <span style="font-weight: bold;">print</span>(e)


<span style="font-weight: bold;">print</span>(<span style="font-style: italic;">'testing end'</span>)
</pre>
</div>
</div>
</div>
<div class="outline-2" id="outline-container-orgc96c976">
<h2 id="orgc96c976">os.walk</h2>
<div class="outline-text-2" id="text-orgc96c976">
<div class="org-src-container">
<pre class="src src-python"><span style="font-weight: bold; font-style: italic;">#</span><span style="font-weight: bold; font-style: italic;">! python3</span>
<span style="font-weight: bold;">import</span> os
<span style="font-weight: bold;">for</span> path, dirs, files <span style="font-weight: bold;">in</span> os.walk(<span style="font-style: italic;">'/usr/local'</span>):
    <span style="font-weight: bold;">print</span>(path) <span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">path is absolute path</span>
</pre>
</div>
</div>
</div>
<div class="outline-2" id="outline-container-orgac0cb1d">
<h2 id="orgac0cb1d">MD5</h2>
<div class="outline-text-2" id="text-orgac0cb1d">
<div class="org-src-container">
<pre class="src src-python"><span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">python 3</span>
<span style="font-weight: bold;">import</span> hashlib
<span style="font-weight: bold; font-style: italic;">m</span> = hashlib.md5()
m.update(<span style="font-weight: bold;">bytes</span>(<span style="font-style: italic;">'abc'</span>, <span style="font-style: italic;">'utf-8'</span>)) <span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">parameter must by bytes</span>
m.update(b<span style="font-style: italic;">'asdf'</span>)
<span style="font-weight: bold;">print</span>(m.digest()) <span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">bytes</span>
<span style="font-weight: bold;">print</span>(m.hexdigest()) <span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">str</span>
</pre>
</div>
</div>
</div>
<div class="outline-2" id="outline-container-orgb0eeb11">
<h2 id="orgb0eeb11">RSA</h2>
<div class="outline-text-2" id="text-orgb0eeb11">
<div class="org-src-container">
<pre class="src src-python"><span style="font-weight: bold;">import</span> rsa
<span style="font-weight: bold;">import</span> base64

(pubKey, prvKey) = rsa.newkeys(1024)
<span style="font-weight: bold;">print</span>(pubKey.n, pubKey.e)
<span style="font-weight: bold; font-style: italic;">message</span> = <span style="font-style: italic;">"hello world"</span>
<span style="font-weight: bold; font-style: italic;">cipher</span> = rsa.encrypt(<span style="font-weight: bold;">bytes</span>(message, <span style="font-style: italic;">'utf-8'</span>), pubKey)
<span style="font-weight: bold; font-style: italic;">encode</span> = base64.b64encode(cipher)
<span style="font-weight: bold;">print</span>(encode)
</pre>
</div>
</div>
</div>
<div class="outline-2" id="outline-container-org899252b">
<h2 id="org899252b">AES</h2>
<div class="outline-text-2" id="text-org899252b">
</div>
<div class="outline-3" id="outline-container-orgd2dec4f">
<h3 id="orgd2dec4f">Encrypt</h3>
<div class="outline-text-3" id="text-orgd2dec4f">
<div class="org-src-container">
<pre class="src src-python"><span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">encoding:utf-8</span>
<span style="font-weight: bold;">from</span> Crypto.Cipher <span style="font-weight: bold;">import</span> AES
<span style="font-weight: bold;">from</span> Crypto <span style="font-weight: bold;">import</span> Random

<span style="font-weight: bold;">import</span> base64

<span style="font-weight: bold;">def</span> <span style="font-weight: bold;">encrypt</span>(data, password, iv):
        <span style="font-weight: bold; font-style: italic;">bs</span> = AES.block_size
        <span style="font-weight: bold; font-style: italic;">pad</span> = <span style="font-weight: bold;">lambda</span> s: s+(bs - <span style="font-weight: bold;">len</span>(s) % bs) * <span style="font-weight: bold;">chr</span>(bs - <span style="font-weight: bold;">len</span>(s) % bs)
        <span style="font-weight: bold; font-style: italic;">cipher</span> = AES.new(password, AES.MODE_CBC, iv)
        <span style="font-weight: bold; font-style: italic;">dataAfterPad</span> = pad(data)
        <span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">print(dataAfterPad + ', lenth is ' + str(len(dataAfterPad)))</span>
        <span style="font-weight: bold; font-style: italic;">data</span> = cipher.encrypt(dataAfterPad)
        <span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">data = iv + data</span>
        <span style="font-weight: bold;">return</span> data

<span style="font-weight: bold; font-style: italic;">cipher</span> = encrypt(<span style="font-style: italic;">'hello world'</span>, <span style="font-style: italic;">')O[NB]6,YF}+efca'</span>,<span style="font-style: italic;">'L+\~f4,Ir)b$=pkf'</span>)
<span style="font-weight: bold;">print</span>(<span style="font-style: italic;">'cipher length is '</span> + <span style="font-weight: bold;">str</span>(<span style="font-weight: bold;">len</span>(cipher)))
<span style="font-weight: bold;">print</span>(<span style="font-style: italic;">'to base64:'</span>)
<span style="font-weight: bold; font-style: italic;">encoded</span> = base64.b64encode(cipher)
<span style="font-weight: bold;">print</span>(encoded)

<span style="font-weight: bold; font-style: italic;"># </span><span style="font-weight: bold; font-style: italic;">fNeN/G8uqwBvCF+DBs4h6A==</span>
</pre>
</div>
<pre class="example">
# AES_encryptResult.txt
hello world, lenth is 16
fNeN/G8uqwBvCF+DBs4h6A==
</pre>
</div>
</div>
<div class="outline-3" id="outline-container-org9aa5518">
<h3 id="org9aa5518">Decrypt</h3>
<div class="outline-text-3" id="text-org9aa5518">
<div class="org-src-container">
<pre class="src src-python"><span style="font-weight: bold;">from</span> Crypto.Cipher <span style="font-weight: bold;">import</span> AES
<span style="font-weight: bold;">from</span> Crypto <span style="font-weight: bold;">import</span> Random

<span style="font-weight: bold;">import</span> base64

<span style="font-weight: bold;">def</span> <span style="font-weight: bold;">decrypt</span>(data, password, iv):
        <span style="font-weight: bold; font-style: italic;">unpad</span> = <span style="font-weight: bold;">lambda</span> s : s[0:-<span style="font-weight: bold;">ord</span>(s[-1])]
        <span style="font-weight: bold; font-style: italic;">cipher</span> = AES.new(password, AES.MODE_CBC, iv)
        <span style="font-weight: bold; font-style: italic;">clear</span> = cipher.decrypt(data)
        <span style="font-weight: bold; font-style: italic;">data</span> = unpad(clear)
        <span style="font-weight: bold;">return</span> data

<span style="font-weight: bold; font-style: italic;">password</span> = <span style="font-style: italic;">')O[NB]6,YF}+efca'</span>
<span style="font-weight: bold; font-style: italic;">iv</span> = <span style="font-style: italic;">'L+\~f4,Ir)b$=pkf'</span>

<span style="font-weight: bold; font-style: italic;">cipher</span> =<span style="font-style: italic;">'fNeN/G8uqwBvCF+DBs4h6A=='</span>
<span style="font-weight: bold; font-style: italic;">cipherBytes</span> = base64.b64decode(cipher)
<span style="font-weight: bold; font-style: italic;">clearText</span> = decrypt(cipherBytes, password, iv)
<span style="font-weight: bold;">print</span>(<span style="font-style: italic;">'clear text is: '</span> + clearText)
</pre>
</div>
</div>
</div>
<div class="outline-3" id="outline-container-org5d05284">
<h3 id="org5d05284">AESCipher Class</h3>
<div class="outline-text-3" id="text-org5d05284">
<div class="org-src-container">
<pre class="src src-python"><span style="font-weight: bold;">from</span> Crypto.Cipher <span style="font-weight: bold;">import</span> AES

<span style="font-weight: bold; font-style: italic;">BS</span> = 16
<span style="font-weight: bold; font-style: italic;">pad</span> = <span style="font-weight: bold;">lambda</span> s: s + (BS - <span style="font-weight: bold;">len</span>(s) % BS) * <span style="font-weight: bold;">chr</span>(BS - <span style="font-weight: bold;">len</span>(s) % BS) 
<span style="font-weight: bold; font-style: italic;">unpad</span> = <span style="font-weight: bold;">lambda</span> s : s[0:-<span style="font-weight: bold;">ord</span>(s[-1])]

<span style="font-weight: bold;">class</span> <span style="font-weight: bold; text-decoration: underline;">AESCipher</span>:
    <span style="font-weight: bold;">def</span> <span style="font-weight: bold;">__init__</span>( <span style="font-weight: bold;">self</span>, key, iv):
        <span style="font-style: italic;">"""</span>
<span style="font-style: italic;">        Requires hex encoded param as a key</span>
<span style="font-style: italic;">        """</span>
        <span style="font-weight: bold;">self</span>.key = key
        <span style="font-weight: bold;">self</span>.iv = iv

    <span style="font-weight: bold;">def</span> <span style="font-weight: bold;">encrypt</span>( <span style="font-weight: bold;">self</span>, raw ):
        <span style="font-style: italic;">"""</span>
<span style="font-style: italic;">        Returns hex encoded encrypted value!</span>
<span style="font-style: italic;">        """</span>
        <span style="font-weight: bold; font-style: italic;">raw</span> = pad(raw)
        <span style="font-weight: bold; font-style: italic;">cipher</span> = AES.new( <span style="font-weight: bold;">self</span>.key, AES.MODE_CBC, <span style="font-weight: bold;">self</span>.iv )
        <span style="font-weight: bold;">return</span> ( <span style="font-weight: bold;">self</span>.iv + cipher.encrypt( raw ) ).encode(<span style="font-style: italic;">"hex"</span>)

    <span style="font-weight: bold;">def</span> <span style="font-weight: bold;">decrypt</span>( <span style="font-weight: bold;">self</span>, enc ):
        <span style="font-style: italic;">"""</span>
<span style="font-style: italic;">        Requires hex encoded param to decrypt</span>
<span style="font-style: italic;">        """</span>
        <span style="font-weight: bold; font-style: italic;">iv</span> = enc[:16]
        <span style="font-weight: bold; font-style: italic;">enc</span>= enc[16:]
        <span style="font-weight: bold; font-style: italic;">cipher</span> = AES.new(<span style="font-weight: bold;">self</span>.key, AES.MODE_CBC, <span style="font-weight: bold;">self</span>.iv )
        <span style="font-weight: bold;">return</span> unpad(cipher.decrypt( enc))

<span style="font-weight: bold;">if</span> <span style="font-weight: bold;">__name__</span>== <span style="font-style: italic;">"__main__"</span>:
    <span style="font-weight: bold; font-style: italic;">key</span> = <span style="font-style: italic;">"98A5FBEF01AE49C9"</span>
    <span style="font-weight: bold; font-style: italic;">ciphertext</span> = <span style="font-style: italic;">"4ca00ff4c898d61e1edbf1800618fb2828a226d160dad07883d04e008a7897ee2e4b7465d5290d0c0e6c6822236e1daafb94ffe0c5da05d9476be028ad7c1d81"</span>;
    <span style="font-weight: bold; font-style: italic;">key</span>=key[:32]
    <span style="font-weight: bold; font-style: italic;">decryptor</span> = AESCipher(key, <span style="font-style: italic;">'BD2E83C829AB6B4E'</span>)
    <span style="font-weight: bold; font-style: italic;">plaintext</span> = decryptor.decrypt(ciphertext)
<span style="font-weight: bold;">print</span>(<span style="font-style: italic;">"%s"</span> % plaintext)
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="status" id="postamble">
<p class="date">Date: 2017-4-23 2018-11-21 2017-09-20 2017-04-23 2017-04-23 2017-09-30 2017-04-23 2018-11-21 2017-08-10 2017-06-30 2017-04-23 2017-04-23 2017-04-23 2017-04-23</p>
<p class="author">Author: gdme1320</p>
<p class="validation"><a href="http://validator.w3.org/check?uri=referer">Validate</a></p>
</div>
